import { AlertController } from '@ionic/angular';
import { Component, Input, OnInit } from '@angular/core';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { EventService } from 'src/app/shared/service/event.service';
import { HttpService } from 'src/app/shared/service/http.service';
import { PageModalService } from 'src/app/shared/service/page-modal-service';

@Component({
  selector: 'app-address-list',
  templateUrl: './address-list.component.html',
  styleUrls: ['./address-list.component.scss'],
})
export class AddressListComponent implements OnInit {
  pageNo = 1;
  addressShow = false;
  isClick = false;
  item: any;
  dataIndex: any; // 当前地址的下标
  tag: any;
  nomalArr = [];
  disabledArr = [];
  tips = false;
  // 组件数据
  @Input() tagData: any = {};
  ids: any;
  constructor(
    private httpService: HttpService,
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private eventService: EventService,
    public alertController: AlertController,


  ) { }

  ngOnInit() {
    if (this.tagData.data.submit && this.tagData.data.submit.content) {
      this.tagData.data.submit.content.pageNo = 2; // page返回初始PageNo 1 ;为了直接是
    }
    // 否后面返回submit请求下一页
    // 监听多选后
    if (this.eventService.eventEmit.listenerCount('auditNow') > 0) {
      this.eventService.eventEmit.removeListener('auditNow');
    }
    this.eventService.eventEmit.on('auditNow', res => {
      console.log(res);
      const ids = [];
      this.tagData.data.data.forEach(element => {
        if (element.checked) {
          ids.push(element.id);
        }
      });
      if (ids.length === 0 && !res.noNeedChoose) {
        this.ids = '';
        return;
      }
      this.ids = ids.join(',');

      if (res.target) {
        this.showModal(res);
      } else {
        // submit
        this.presentAlertWithMsgBtn(res);

      }

    });

    this.eventService.eventEmit.on('addressManage', res => {
      this.addressShow = !this.addressShow;
      if (this.isClick) {
        // 修改默认地址
        this.postAddressManageData(this.item);
        this.isClick = false;
      }
    });

    this.tagData.data.data.forEach(e => {
      if (e.secondRowLeft && e.secondRowLeft.tag) {
        e.check_show = true;
      } else {
        e.check_show = false;
      }
      if ((e.checked === 'true' && !this.appGlobalService.shopAddressSelectItemName)
        || (e.id === this.appGlobalService.addressEventResultValue && this.appGlobalService.shopAddressSelectItemName)) {
        this.appGlobalService.needShopShipAddressId = false;
        e.checked = 'true';
      } else if (e.checked === undefined) {

      } else {
        e.checked = 'false';
      }
      if (e.disabled !== undefined) {
        this.disabledArr.push(e);
      } else {
        if (e.checked === 'true') {
          this.nomalArr.unshift(e);
        } else {
          this.nomalArr.push(e);
        }
      }
    });

    if (this.eventService.eventEmit.listenerCount('updateAddress') > 0) {
      this.eventService.eventEmit.removeListener('updateAddress');
    }

    const that = this;
    this.eventService.eventEmit.on('updateAddress', item => {

      console.log('更新的地址id:' + JSON.stringify(item));

      that.updateItem(item.id, true);
    });

    if (that.tagData.data.data.length < 1 || !that.tagData.data.data) {
      this.tips = true;
    }
  }

  updateItem(id, isNew) {
    const that = this;
    const page: any = this.appGlobalService.getCurrentTarget();
    if (page.params) {
    } else {
      page.params = {};
    }
    page.params.shop_ship_address_id = id;
    page.params.shop_local_address_id = id;
    this.httpService.post('application/page', page, async res => {
      const tagData = JSON.parse(res.script).views[0].tags;
      tagData.forEach(element => {
        if (element.style === 'addressManageListTag' && element.data && element.data.data[element.data.data.length - 1]) {
          let newData: any;
          try {
            element.data.data.forEach((e, index) => {
              if (e.id === id) {
                newData = element.data.data[index];
                if (newData.secondRowLeft.tag) {
                  newData.check_show = true;
                }

                if (this.nomalArr && this.nomalArr.length > 0) {
                  this.nomalArr.forEach((el, index) => {
                    if (el.secondRowLeft.tag && newData.secondRowLeft.tag) { // 设置新默认地址 会出现两个默认的情况
                      el.check_show = false;
                      el.secondRowLeft.tag.lable = "";
                    }

                    if (el.id === newData.id) {
                      isNew = false;
                      if (newData.disabled !== undefined) {  // 如果可选地址区域变化
                        this.nomalArr.splice(index, 1);
                        isNew = true;
                      }
                    }
                  });
                }
                if (this.disabledArr && this.disabledArr.length > 0) {
                  this.disabledArr.forEach((e, index) => {
                    if (e.id === newData.id) {
                      isNew = false;
                      if (newData.disabled === undefined) {  // 如果可选地址区域变化
                        this.disabledArr.splice(index, 1);
                        isNew = true;
                      }
                    }

                    if (e.secondRowLeft.tag) {
                      e.check_show = false;
                      e.secondRowLeft.tag.lable = "";
                    }
                  });
                }

                if (isNew) {
                  // 新数据
                  if (newData.disabled === undefined) {
                    that.nomalArr.unshift(newData);
                  } else {
                    that.disabledArr.unshift(newData);
                  }

                  if (that.tagData.data.data.length < 1 || !that.tagData.data.data) {
                    that.tagData.data.data.unshift(newData);
                    that.tips = false;
                  }
                } else {
                  if (newData.disabled === undefined) {
                    that.nomalArr[that.dataIndex] = newData;
                  } else {
                    that.disabledArr[that.dataIndex] = newData;
                  }
                }
                throw 'quit';
              }
            });
          } catch (error) {
            if (error !== 'quit') {
              throw error;
            }
          }
        } else if (element.style === 'tag.AppSimpleDetailTagLogic' && element.data && element.data.cssType === '6') {

          // cssType 为6表示选择地址
          localStorage.setItem('updateAddressElement', '1');
          this.eventService.eventEmit.emit('updateAddressElement', element);

        }

      });
    });
  }

  showModal(link) {
    const that = this;

    link.params.id = this.ids;

    this.pageModalService.openPage(link, '', result => {
      if (result) {
        console.log('test' + JSON.stringify(result));
      }
      if (link.params && link.params.refresh && link.params.refresh !== undefined) {
        // 刷新页面
        this.httpService.reloadCurrentPage();
        setTimeout(() => {
          localStorage.setItem("needRefresh", "true");
        }, 100);
      }
    });

  }
  async presentAlertWithMsgBtn(submit, msg?) {
    const that = this;
    const alert = await this.alertController.create({
      message: submit.text ? submit.text : msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: '确定',
          handler: () => {
            if (submit.content.listKey) {
              submit.content[submit.content.listKey] = this.ids;
            } else {
              submit.content.id = this.ids;
            }
            const params = {
              content: submit.content,
              id: submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              if (res.success) {
                // that.appGlobalService.reloadCurrentPage();
                this.eventService.eventEmit.emit('submitRes', JSON.stringify({ res, submit }));
              }
              if (res.message && res.message.length > 0) {
                this.appGlobalService.showToast(res.message, 1500, "middle");
              }

            });
          }
        }
      ]
    });
    await alert.present();
  }


  modify(event, link, i) {
    this.dataIndex = i;
    this.pageModalService.openPage(link);
    if (event) {
      event.stopPropagation();
    }
  }
  // 上滑加载
  loadMoreData(event) {
    this.pageNo = this.pageNo + 1;
    if (this.tagData.data.data.length >= this.tagData.data.pageTotal) {
      event.target.disabled = true;
      // this.appGlobalService.showToast("没有数据了...", 1000, "middle");
      // event.complete();
      return;
    }
    if (this.tagData.data.submit) {
      if (this.tagData.data.submit.content) {
        this.tagData.data.submit.content.pageNo = this.pageNo;
      }
      this.tagData.data.submit.sessionId = localStorage.getItem("sessionId");
    }

    this.httpService.post(
      "application/submit",
      this.tagData.data.submit,
      res => {
        // 请求数据成功
        if (res.success) {
          const resList = res.data.data;
          this.tagData.data.submit = res.data.submit;
          // 追加返回数据
          if (resList && resList.length > 0) {
            // 追加数据
            resList.map(item => {
              this.tagData.data.data.push(item);
            });
          } else {
            event.target.disabled = true;
            // 没有数据了
            // this.appGlobalService.showToast("没有数据了...", 1000, "middle");
          }
        } else {
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
        }
        event.target.complete();
      },
      err => {

        // 请求数据失败
        this.appGlobalService.showToast(err.message, 2000, "middle");
        event.target.complete();
      }
    );
  }
  // 修改默认地址
  defaultAddress(item, event, i) {
    if (event) {
      event.stopPropagation();
    }
    this.item = item;
    this.dataIndex = i;
    if (item.check_show !== true) {

      this.nomalArr.forEach(e => {
        e.check_show = false;
      });
      this.disabledArr.forEach(e => {
        e.check_show = false;
      });

      item.check_show = true;
      this.isClick = true;
    }
  }
  // 删除功能
  async del(event, submit, item, msg?, i?) {
    if (event) {
      event.stopPropagation();
    }
    const that = this;
    const alert = await this.alertController.create({
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: '确定',
          handler: async () => {
            if (item.disabled === undefined) {
              that.nomalArr.forEach((e, index) => { // 删除地址操作
                if (i === index) {
                  submit.content.id = e.id;
                  that.nomalArr.splice(index, 1);
                }
              });
            } else if (item.disabled) {
              that.disabledArr.forEach((e, index) => { // 删除地址操作
                if (i === index) {
                  submit.content.id = e.id;
                  that.disabledArr.splice(index, 1);
                }
              });
            }
            if (that.disabledArr.length < 1 && that.nomalArr.length < 1) {
              that.tagData.data.data.splice(0, 1);
              that.tips = true; // 提示有无数据
            }
            // 清除选择的地址信息
            if (item.checked && item.checked === 'true' || item.id === this.appGlobalService.addressEventResultValue) {
              this.appGlobalService.shopAddressSelectItemName = '';
              this.appGlobalService.shopAddressSelectItemLocation = '';
              this.appGlobalService.shopAddressSelectItemId = '';
              this.appGlobalService.addressEventResultValue = '';
            }
            const params = {
              content: submit.content,
              id: submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              if (res.success) {
                this.appGlobalService.showToast(res.message, 1500, "middle");
                if (this.appGlobalService.shopAddressSelectItemId === item.id) {
                  this.appGlobalService.shopAddressSelectItemId = '';
                }
              }
            });
          }
        }
      ]
    });
    await alert.present();
  }

  postAddressManageData(item) {
    item.thirdRowLeft.chooseButton.sessionId = localStorage.getItem('sessionId');
    this.httpService.post('application/submit', item.thirdRowLeft.chooseButton, res => {
      // 请求成功
      if (res.success) {
        this.updateItem(item.thirdRowLeft.chooseButton.content.shop_ship_address_id, false);
      } else {
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    });
  }

  // tslint:disable-next-line:use-life-cycle-interface
  ngOnDestroy(): void {
    this.isClick = false;  // 离开当前页面赋值
  }
  selectItem(event, item) {
    if (event) {
      event.stopPropagation();
    }

    // 2024.07.06 add by andrew.wen
    if (item.eventName) {
      if (item.secondRowLeft &&
        item.secondRowLeft.firstText &&
        item.secondRowLeft.firstText.label) {
        this.appGlobalService.locationAddressLabel = item.secondRowLeft.firstText.label;
      }
      if (item.needRefreshTab && item.needRefreshTab !== '') {
        localStorage.setItem('needRefreshTab' + item.needRefreshTab, 'true');
      }
    }
    if (item.action && item.action.submit) {

      const params = {
        content: item.action.submit.content,
        id: item.action.submit.id,
        sessionId: localStorage.getItem('sessionId')
      };
      // 请求获取新数据
      this.httpService.post('application/submit', params, res => {

        // 请求数据成功
        if (res.success) {
          this.success(res, item.action);
        } else {
          this.appGlobalService.showToast(res.message, 1500, 'middle');
        }
      },
        err => {

        });

    } else if (item.submitBtn && item.submitBtn.submitBtnsub && item.checked !== undefined) {
      const params = {
        content: item.submitBtn.submitBtnsub.content,
        id: item.submitBtn.submitBtnsub.id,
        sessionId: localStorage.getItem('sessionId')
      };
      this.httpService.post('application/submit', params, res => {
        // 请求数据成功
        if (res.success) {
          const addressItem = {
            id: item.id,
          };
          this.appGlobalService.shopAddressSelectItemId = item.id;
          // if (this.appGlobalService.clientType !== 'js') { // 非商户端 update by andrew.wen 2024.02.26 配置改成商户端与用户端一致了

          if (item.secondRowLeft
            && item.secondRowLeft.firstText
            && item.secondRowLeft.firstText.label
          ) {
            this.appGlobalService.shopAddressSelectItemLocation = item.secondRowLeft.firstText.label;
          }
          if (item.firstRowLeft
            && item.firstRowLeft.secondText
            && item.firstRowLeft.secondText.label) {
            this.appGlobalService.shopAddressSelectItemPhone = item.firstRowLeft.secondText.label;
          }

          if (item.firstRowLeft
            && item.firstRowLeft.firstText && item.firstRowLeft.firstText.label) {
            this.appGlobalService.shopAddressSelectItemName = item.firstRowLeft.firstText.label;
          }
          // 2.2.2 新增自定义参数
          if (res.data && res.data.eventResult) {
            this.appGlobalService.addressEventResultValue = res.data.eventResult;
            if (res.params && res.params.addressEventResultName !== undefined) {
              this.appGlobalService.addressEventResultName = res.params.addressEventResultName;
            }
          }

          this.eventService.emit("selectAddress", addressItem);

          this.appGlobalService.popTarget();
          this.appGlobalService.goBack();

          if (item.needRefresh) {
            this.appGlobalService.needShopShipAddressId = true;
            if (!window['tabs']) {
              localStorage.setItem("needRefresh", "true");
              this.appGlobalService.popTarget();
              this.appGlobalService.goBack();
            } else {
              setTimeout(() => {
                localStorage.setItem("needRefresh", "true");
                this.appGlobalService.popTarget();
                this.appGlobalService.goBack();
              }, 150);
            }
          }

        }
      });
    } else if (item.checked !== undefined) {
      const addressItem = {
        id: item.id,
      };
      this.appGlobalService.shopAddressSelectItemId = item.id;

      if (item.secondRowLeft
        && item.secondRowLeft.firstText
        && item.secondRowLeft.firstText.label
      ) {
        this.appGlobalService.shopAddressSelectItemLocation = item.secondRowLeft.firstText.label;
      }
      if (item.firstRowLeft
        && item.firstRowLeft.secondText
        && item.firstRowLeft.secondText.label) {
        this.appGlobalService.shopAddressSelectItemPhone = item.firstRowLeft.secondText.label;
      }

      if (item.firstRowLeft
        && item.firstRowLeft.firstText && item.firstRowLeft.firstText.label) {
        this.appGlobalService.shopAddressSelectItemName = item.firstRowLeft.firstText.label;
      }

      this.eventService.emit("selectAddress", addressItem);


      this.appGlobalService.popTarget();
      this.appGlobalService.goBack();
    } else if (item.submitBtn && item.submitBtn.submitBtnsub) {
      this.appGlobalService.shopAddressSelectItemId = item.id;
      const params = {
        content: item.submitBtn.submitBtnsub.content,
        id: item.submitBtn.submitBtnsub.id,
        sessionId: localStorage.getItem('sessionId')
      };
      this.httpService.post('application/submit', params, res => {
        // 请求数据成功
        if (res.success) {

          // 2024.04.12 
          if (res.params.needStorePosition !== undefined && res.params.needStorePosition === 'true') {





            if (res.data && res.data.eventResult) {
              const results = res.data.eventResult.split(',');
              if (results.length > 0 && res.data.eventResult.indexOf('.') > -1) {
                this.appGlobalService.getAddressLat = results[0];
                this.appGlobalService.getAddressLng = results[1];
                if (results[0] && results[1]) {
                  this.eventService.eventEmit.emit('getAddressByPoint', '' + results[1] + ',' + results[0]);
                }
              }
              this.appGlobalService.addressEventResultValue = res.data.eventResult;
              if (res.params && res.params.addressEventResultName !== undefined) {
                this.appGlobalService.addressEventResultName = res.params.addressEventResultName;
              }
            }
          }

          if (!window['tabs']) {
            localStorage.setItem("needRefresh", "true");
            this.appGlobalService.popTarget();
            this.appGlobalService.goBack();
          } else {
            setTimeout(() => {
              localStorage.setItem("needRefresh", "true");
              this.appGlobalService.popTarget();
              this.appGlobalService.goBack();
            }, 150);
          }
        }
      });
    }




  }


  success(res, item) {

    if (item.back) {
      if (Number(item.back) < 0) {
        const back = Math.abs(Number(item.back));
        for (let index = 0; index < back; index++) {
          this.appGlobalService.popTarget();
        }
        this.appGlobalService.goBack(Number(item.back));
      } else if (Number(item.back) === 0) {
        setTimeout(() => {
          this.eventService.eventEmit.emit("reloadCurrentPage", "reloadCurrentPage");
          if (res.message) {
            this.appGlobalService.showToast(res.message, 1000, "middle");
          }
        }, 1000);

      } else {
        this.appGlobalService.goBack(Number(item.back));
      }
      localStorage.setItem("needRefresh", "true");
    }
  }


}
